import {UPLOAD_INFO, ALLOW_TYPE, CHUNK_SIZE,API} from './config'
import axios from 'axios'

;((doc)=>{
    const uploadProgress = doc.querySelector('#uploadProgress');
    const videoUploader = doc.querySelector('#videoUploader');
    const uploadInfo = doc.querySelector('#uploadInfo');
    const uploadBtn = doc.querySelector('#uploadBtn');

    // 保留上传的大小
    let uploadSize = 0;

    const init = () => {
        bindEvent();
    }   

    function bindEvent() {
        uploadBtn.addEventListener('click',uploadVideo,false);
    }

    async function uploadVideo() {
        const file = videoUploader.files[0];
        //  file没上传为undefined
        if(!file){
            uploadInfo.innerText = UPLOAD_INFO['NO_files'];
            return;
        }
        // 判断上传文件的类型
        if( !ALLOW_TYPE[file.type] ){
            uploadInfo.innerText = UPLOAD_INFO['FileTypeError']
        }else{
            uploadInfo.innerText = UPLOAD_INFO['FileTypeSuccess'] + 1
        }
        // 上传逻辑 name size type
        const { name, size ,type } = file
        const fileName = new Date().getTime() + name
        uploadProgress.max = size

        while(uploadSize < size){
            const fileChunk = file.slice(uploadSize, uploadSize + CHUNK_SIZE);
            const formData = createFormData({name, size ,type,fileName,uploadSize,file:fileChunk})

            // 发请求到后端
            try{
                const res =  await axios.post(API.URL,formData)
                console.log(res.data.data)
            } catch(e){
                uploadInfo.innerText = `${UPLOAD_INFO['upload_Error']}(${e})`
                return
            }
            uploadSize += fileChunk.size
            uploadProgress.value = uploadSize
        }
        uploadInfo.innerText = UPLOAD_INFO['FileTypeSuccess'] + 2
        videoUploader.value = null
    }

    function createFormData( {name, size ,type,fileName,uploadSize,file} ){
        const fd = new FormData()
        fd.append('name' , name);
        fd.append('size' , size);
        fd.append('type' , type);
        fd.append('fileName' , fileName);
        fd.append('uploadSize' , uploadSize);
        fd.append('file' , file);

        return fd
    }
    
    init();
})(document);